package com.cq.hd.product.factory;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cq.hd.common.constant.Constant;
import com.cq.hd.common.enums.biz.*;
import com.cq.hd.common.response.Throw;
import com.cq.hd.common.utils.BeanUtils;
import com.cq.hd.common.utils.LocalDateUtil;
import com.cq.hd.common.utils.NoUtils;
import com.cq.hd.member.api.TbBusinessApi;
import com.cq.hd.member.api.dto.UpdateActiveCountDto;
import com.cq.hd.member.api.vo.BusinessVo;
import com.cq.hd.order.api.TbOrderApi;
import com.cq.hd.product.api.dto.*;
import com.cq.hd.product.mapper.*;
import com.cq.hd.product.po.*;
import com.cq.hd.product.service.TbActiveLabelService;
import com.cq.hd.product.validator.ActivePublishValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class EnrollActiveReleaseHandler extends AbstractActiveReleaseHandler {

    @Autowired
    private TbActiveAgentMapper activeAgentMapper;

    @Autowired
    private TbActiveRedPacketMapper activeRedPacketMapper;

    @Autowired
    private TbActiveStepPriceMapper activeStepPriceMapper;

    @Autowired
    private TbActiveEnrollInfoMapper activeEnrollInfoMapper;

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Autowired
    private TbActiveMapper activeMapper;

    @Autowired
    private TbActiveLabelService activeLabelService;

    @Autowired
    private TbBusinessApi businessApi;

    @Autowired
    private TbOrderApi orderApi;

    @Value("${spring.profiles.active}")
    private String env;

    @Override
    protected Integer getType() {
        return ActiveTypeEnum.ENROLL.getValue();
    }

    @Override
    public Long saveActiveData(ActiveReleaseDto activeReleaseDto) {
//        if (activeReleaseDto.getLimitBuyNum() == null) {
//            activeReleaseDto.setLimitBuyNum(99999999);
//        }
        // 报名次数限制前端改成限购数量
//        if (activeReleaseDto.getLimitEnrollNum() == null || activeReleaseDto.getLimitEnrollNum() == 0) {
//            Integer limitBuyBum = Optional.ofNullable(activeReleaseDto.getLimitBuyNum())
//                    .orElse(99999999);
            activeReleaseDto.setLimitEnrollNum(activeReleaseDto.getLimitBuyNum());
//        }

        // 表单校验
        ActivePublishValidator.validate(activeReleaseDto);

        String activeTitle = activeReleaseDto.getActiveTitle();
        String activeImg = activeReleaseDto.getActiveImg();
        List<ActiveContent> activeContents = activeReleaseDto.getActiveContents();
        BigDecimal activePrice = activeReleaseDto.getActivePrice();
        BigDecimal originPrice = activeReleaseDto.getOriginPrice();
        Integer enrollNum = activeReleaseDto.getEnrollNum();
        // 活动状态（1-仅保存，2-去发布）
        Integer activeState = activeReleaseDto.getActiveState();
        // 是否是所有经纪人可推广：1-否，2-是
        Integer agentNumState = activeReleaseDto.getAgentNumState();
        List<Long> agentIds = activeReleaseDto.getAgentIds();
        String startTime = activeReleaseDto.getStartTime();
        String endTime = activeReleaseDto.getEndTime();
        String validStartTime = activeReleaseDto.getValidStartTime();
        String validEndTime = activeReleaseDto.getValidEndTime();
        Integer noFullAutoRefundState = activeReleaseDto.getNoFullAutoRefundState();
        // 是否是零元购活动（1-不是，2-是）
        Integer zeroState = activeReleaseDto.getZeroState();

        if (VerifyTypeEnum.TYF.getValue().equals(activeReleaseDto.getVerifyType())) {
            if (StrUtil.isEmpty(activeReleaseDto.getPftProduct())) {
                Throw.isBusinessException("票付通产品ID不能为空");
            }
            if (StrUtil.isEmpty(activeReleaseDto.getPftTicket())) {
                Throw.isBusinessException("票付通门票ID不能为空");
            }
            if (StrUtil.isEmpty(activeReleaseDto.getPftSupplier())) {
                Throw.isBusinessException("票付通供应商ID不能为空");
            }
            boolean flag = orderApi.pftOrderPreCheck(activeReleaseDto.getPftSupplier()
                    , activeReleaseDto.getPftProduct(), activeReleaseDto.getPftTicket()).unpack();
            if (!flag) {
                Throw.isBusinessException("票付通参数设置有误，请确认后重试");
            }
        }

        if (zeroState == null || ZeroStateEnum.typeOf(zeroState) == null) {
            Throw.isBusinessException("请选择零元购状态");
        }

        if (activeState == null || (activeState != 1 && activeState != 2)) {
            Throw.isBusinessException("活动状态值错误");
        }

        if (StringUtils.isEmpty(activeTitle)) {
            Throw.isBusinessException("请输入活动标题");
        }

        if (StringUtils.isEmpty(activeImg)) {
            Throw.isBusinessException("请上传活动图片");
        }

        if (CollectionUtils.isEmpty(activeContents)) {
            Throw.isBusinessException("请输入活动内容");
        } else {
            for (ActiveContent activeContent : activeContents) {
                String content = activeContent.getContent();
                if (StringUtils.isEmpty(content)) {
                    Throw.isBusinessException("请输入活动内容");
                }
            }
        }

        // 未满员是否自动退款:1-是，2-否
        if (noFullAutoRefundState == null || NoFullAutoRefundStateEnum.typeOf(noFullAutoRefundState) == null) {
            Throw.isBusinessException("请设置未满员是否自动退款状态");
        }

        if (StringUtils.isEmpty(activeReleaseDto.getAddress())
                || StringUtils.isEmpty(activeReleaseDto.getProvinceName())
                || StringUtils.isEmpty(activeReleaseDto.getCityName())) {
            Throw.isBusinessException("请填写活动地址");
        }

        // 校验活动时间
        if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)) {
            Throw.isBusinessException("请设置活动时间");
        }

        LocalDateTime startLocalDateTime = null;
        LocalDateTime endLocalDateTime = null;
        try {
            startLocalDateTime = LocalDateUtil.toLocalDateTime(startTime, Constant.YYYY_MM_DD_HH_MM_SS);
            endLocalDateTime = LocalDateUtil.toLocalDateTime(endTime, Constant.YYYY_MM_DD_HH_MM_SS);
        } catch (Exception e) {
            Throw.isBusinessException("活动时间设置有误");
        }

        LocalDateTime nowLocalDateTime = LocalDateUtil.getNowLocalDateTime();

        // 活动开始时间，不能早于当前时间
        if (nowLocalDateTime.compareTo(startLocalDateTime) >= 0) {
            Throw.isBusinessException("活动开始时间不能早于当前时间");
        }

        // 活动开始时间，不能大于活动结束时间
        if (startLocalDateTime.compareTo(endLocalDateTime) >= 0) {
            Throw.isBusinessException("活动开始时间不能晚于活动结束时间");
        }

        if (StringUtils.isEmpty(validStartTime) || StringUtils.isEmpty(validEndTime)) {
            Throw.isBusinessException("请设置使用时间");
        }

        LocalDateTime validStartLocalDateTime = null;
        LocalDateTime validEndLocalDateTime = null;
        try {
            validStartLocalDateTime = LocalDateUtil.toLocalDateTime(validStartTime, Constant.YYYY_MM_DD_HH_MM_SS);
            validEndLocalDateTime = LocalDateUtil.toLocalDateTime(validEndTime, Constant.YYYY_MM_DD_HH_MM_SS);
        } catch (Exception e) {
            Throw.isBusinessException("使用时间设置有误");
        }

        // 活动有效开始时间，不能大于活动有效结束时间
        if (validStartLocalDateTime.compareTo(validEndLocalDateTime) >= 0) {
            Throw.isBusinessException("活动有效开始时间不能晚于活动有效结束时间");
        }

        // 活动结束时间，不能大于活动有效开始时间
        // 没有开启未满员自动退的报名活动，有效时间是可以和起止时间同步的，只有开启了未满员自动退，才需要限制
        if (NoFullAutoRefundStateEnum.YES.getValue().equals(noFullAutoRefundState)) {
            if (endLocalDateTime.compareTo(validStartLocalDateTime) >= 0) {
                Throw.isBusinessException("活动结束时间不能晚于活动有效开始时间");
            }
        }

        // 活动时间不能超过360天
        long seconds = LocalDateUtil.getDurationToLocalDateTime(validStartLocalDateTime, validEndLocalDateTime).getSeconds();
        if (seconds > 0) {
            long days = (seconds % 60 % 60 % 24) > 0 ? (seconds / 60 / 60 / 24) + 1 : (seconds / 60 / 60 / 24);
            if (days > 360) {
                Throw.isBusinessException("活动时间不能超过360天");
            }
        }

        // 使用时间不能超过360天
        seconds = LocalDateUtil.getDurationToLocalDateTime(startLocalDateTime, endLocalDateTime).getSeconds();
        if (seconds > 0) {
            long days = (seconds % 60 % 60 % 24) > 0 ? (seconds / 60 / 60 / 24) + 1 : (seconds / 60 / 60 / 24);
            if (days > 360) {
                Throw.isBusinessException("使用时间不能超过360天");
            }
        }

        // 是否是阶梯价格(1-否，2-是)
        Integer stepPriceState = activeReleaseDto.getStepPriceState();
        if (stepPriceState == null || StepPriceStateEnum.typeOf(stepPriceState) == null) {
            Throw.isBusinessException("请设置阶梯价格状态");
        }

        // 分销开启状态(1-关闭，2-开启)
        Integer agentState = activeReleaseDto.getAgentState();
        if (agentState == null || AgentStateEnum.typeOf(agentState) == null) {
            Throw.isBusinessException("请选择分销开启状态");
        }

        BigDecimal firstRedPacketAmt = BigDecimal.ZERO;
        ActiveRedPacketSonDto activeRedPacket = activeReleaseDto.getActiveRedPacket();
        if (activeRedPacket != null) {
            if (ZeroStateEnum.YES.getValue().equals(zeroState)) {
                Throw.isBusinessException("0元购活动不能设置红包");
            }

            firstRedPacketAmt = activeRedPacket.getFirstRedPacketAmt();
            if (firstRedPacketAmt == null || firstRedPacketAmt.compareTo(BigDecimal.ZERO) <= 0) {
                Throw.isBusinessException("红包金额必须大于0元");
            }

            Integer redPacketNum = activeRedPacket.getRedPacketNum();
            if (redPacketNum <= 0) {
                Throw.isBusinessException("红包数量必须大于0个");
            }

            Integer validDay = activeRedPacket.getValidDay();
            if (validDay <= 0) {
                Throw.isBusinessException("红包有效期必须大于0天");
            }
        }

        BigDecimal minActivePrice = BigDecimal.ZERO;
        List<ActiveStepPriceSonDto> activeStepPrices = activeReleaseDto.getActiveStepPrices();
        if (StepPriceStateEnum.YES.getValue().equals(stepPriceState)) {
            if (ZeroStateEnum.YES.getValue().equals(zeroState)) {
                Throw.isBusinessException("零元购活动不能设置阶梯价格");
            }

            if (CollectionUtils.isEmpty(activeStepPrices)) {
                Throw.isBusinessException("请设置阶梯价格");
            }

            if (activeStepPrices.size() > 3) {
                Throw.isBusinessException("最多支持3个阶梯价格");
            }

            if (activeStepPrices.size() < 2) {
                Throw.isBusinessException("最少支持2个阶梯价格");
            }

            Map<Integer, ActiveStepPriceSonDto> enrollNumMap = new HashMap<>();
            Map<BigDecimal, ActiveStepPriceSonDto> enrollPriceMap = new HashMap<>();

            // 校验阶梯报名人数和价格
            for (ActiveStepPriceSonDto activeStepPrice : activeStepPrices) {
                Integer getEnrollNum = activeStepPrice.getEnrollNum();
                BigDecimal getEnrollPrice = activeStepPrice.getEnrollPrice();

                if (getEnrollNum <= 0) {
                    Throw.isBusinessException("阶梯报名人数必须大于0个");
                }

                if (getEnrollPrice.compareTo(BigDecimal.ZERO) <= 0) {
                    Throw.isBusinessException("阶梯报名价格必须大于0元");
                }

                if (enrollNumMap.containsKey(getEnrollNum)) {
                    Throw.isBusinessException("阶梯报名人数不能相同");
                }
                enrollNumMap.put(getEnrollNum, activeStepPrice);

                if (enrollPriceMap.containsKey(getEnrollPrice)) {
                    Throw.isBusinessException("阶梯报名金额不能相同");
                }

                enrollPriceMap.put(getEnrollPrice, activeStepPrice);
            }

            // 根据报名人数升序
            List<ActiveStepPriceSonDto> activeStepPriceSons = activeStepPrices.stream()
                    .sorted(Comparator.comparing(ActiveStepPriceSonDto::getEnrollNum))
                    .collect(Collectors.toList());
            // 第一阶梯
            ActiveStepPriceSonDto firstActiveStepPriceSonDto = activeStepPriceSons.get(0);
            Integer firstEnrollNum = firstActiveStepPriceSonDto.getEnrollNum();
            BigDecimal firstEnrollPrice = firstActiveStepPriceSonDto.getEnrollPrice();

            // 第二阶梯
            ActiveStepPriceSonDto secondActiveStepPriceSonDto = activeStepPriceSons.get(1);
            Integer secondEnrollNum = secondActiveStepPriceSonDto.getEnrollNum();
            BigDecimal secondEnrollPrice = secondActiveStepPriceSonDto.getEnrollPrice();

            // 限制第一阶梯人数必须小于第二阶梯，第一阶梯价格必须大于第二阶梯
            if (firstEnrollNum >= secondEnrollNum) {
                Throw.isBusinessException("阶梯二人数需大于阶梯一人数");
            }

            if (firstEnrollPrice.compareTo(secondEnrollPrice) <= 0) {
                Throw.isBusinessException("阶梯二价格需低于阶梯一价格");
            }

            // 返现金额+红包<第一阶梯的价格，返现金额=阶梯价格之间的差价，第一阶梯价格-第二阶梯价格
//            BigDecimal returnAmt = firstEnrollPrice.subtract(secondEnrollPrice);
//            BigDecimal tmpAmt = returnAmt.add(firstRedPacketAmt);
//            if (tmpAmt.compareTo(firstEnrollPrice) >= 0) {
//                Throw.isBusinessException("阶梯间差价+红包金额需小于阶梯一价格");
//            }

            // 第三阶梯
            if (activeStepPriceSons.size() > 2) {
                ActiveStepPriceSonDto threeActiveStepPriceSonDto = activeStepPriceSons.get(2);
                Integer threeEnrollNum = threeActiveStepPriceSonDto.getEnrollNum();
                BigDecimal threeEnrollPrice = threeActiveStepPriceSonDto.getEnrollPrice();

                // 限制第二阶梯人数必须小于第三阶梯，第二阶梯价格必须大于第三阶梯
                if (secondEnrollNum >= threeEnrollNum) {
                    Throw.isBusinessException("阶梯三人数需大于阶梯二人数");
                }

                if (secondEnrollPrice.compareTo(threeEnrollPrice) <= 0) {
                    Throw.isBusinessException("阶梯三价格需低于阶梯二价格");
                }

                // 返现金额+红包<第一阶梯的价格，返现金额=阶梯价格之间的差价，第一阶梯价格-第三阶梯价格
//                returnAmt = firstEnrollPrice.subtract(threeEnrollPrice);
//                tmpAmt = returnAmt.add(firstRedPacketAmt);
//                if (tmpAmt.compareTo(firstEnrollPrice) >= 0) {
//                    Throw.isBusinessException("阶梯间差价+红包金额需小于阶梯一价格");
//                }
            }

            // 以阶梯价格配置的最少人数所对应的价格去计算佣金，而不是最大的价格，去计算佣金比例
            activePrice = firstEnrollPrice;

            // 获取阶梯最小价格
            List<ActiveStepPriceSonDto> activeStepPriceSonDtos = activeStepPrices.stream()
                    .sorted(Comparator.comparing(ActiveStepPriceSonDto::getEnrollPrice).reversed())
                    .collect(Collectors.toList());
            ActiveStepPriceSonDto activeStepPriceSon = activeStepPriceSonDtos.get(0);
            minActivePrice = activeStepPriceSon.getEnrollPrice();

            // 获取阶梯最大人数
            enrollNum = activeStepPriceSons.get(activeStepPriceSons.size() - 1).getEnrollNum();
        }

        // 如果是测试环境，活动价格不能少于0.1元，否则不能少于1元
//        if ("test".equals(env)) {
//        if (activePrice == null || activePrice.compareTo(new BigDecimal("0.1")) < 0) {
//            Throw.isBusinessException("活动价格不能少于0.1元");
//        }
//        } else {
//            if (activePrice == null || activePrice.compareTo(new BigDecimal("1")) < 0) {
//                Throw.isBusinessException("活动价格不能少于1元");
//            }
//        }


        if (ZeroStateEnum.NO.getValue().equals(zeroState)) {
            // 如果存在分销和阶梯情况下，报名活动价格必须大于1元，否则可以是0.1元
            if (StepPriceStateEnum.YES.getValue().equals(stepPriceState) || AgentStateEnum.OPEN.getValue().equals(agentState)) {
                if (activePrice == null || activePrice.compareTo(new BigDecimal("0.1")) < 0) {
                    Throw.isBusinessException("活动价格不能少于0.1元");
                }

                // 报名价格-红包金额必须大于1元
                BigDecimal tmpAmt = activePrice.subtract(firstRedPacketAmt);
                if (tmpAmt.compareTo(new BigDecimal("0.1")) < 0) {
                    Throw.isBusinessException("活动价格-红包金额需大于等于0.1元");
                }
            } else {
                if (activePrice == null || activePrice.compareTo(new BigDecimal("0.1")) < 0) {
                    Throw.isBusinessException("活动价格不能少于0.1元");
                }

                // 报名价格-红包金额必须大于0.1元
                BigDecimal tmpAmt = activePrice.subtract(firstRedPacketAmt);
                if (tmpAmt.compareTo(new BigDecimal("0.1")) < 0) {
                    Throw.isBusinessException("活动价格-红包金额需大于等于0.1元");
                }
            }
        } else {
            activePrice = BigDecimal.ZERO;
        }

        if (originPrice != null && originPrice.compareTo(BigDecimal.ZERO) > 0) {
            if (originPrice.compareTo(new BigDecimal("99999999")) > 0) {
                Throw.isBusinessException("划线价格必须小于99999999元");
            }

            if (originPrice.compareTo(activePrice) < 0) {
                Throw.isBusinessException("划线价格必须大于等于活动价格");
            }
        }

        // 拼团不用校验报名人数
        if (activeReleaseDto.getPromotionType() == null) {
            // 报名人数必填
            if (enrollNum == null || enrollNum <= 0) {
                Throw.isBusinessException("报名人数必须大于0个");
            }

            if (enrollNum > 99999999) {
                Throw.isBusinessException("报名人数不能超过99999999个");
            }
        }

        BigDecimal actCommissionAmt = BigDecimal.ZERO;
        // 校验分销
        if (AgentStateEnum.OPEN.getValue().equals(agentState)) {
            BigDecimal commissionAmt = activeReleaseDto.getCommissionAmt();
            BigDecimal commissionRate = activeReleaseDto.getCommissionRate();
            // 默认佣金类型：0-无，1-佣金，2-佣金比例
            Integer defaultCommissionType = activeReleaseDto.getDefaultCommissionType();
            String otherEquity = activeReleaseDto.getOtherEquity();

            if (defaultCommissionType == null || DefaultCommissionTypeEnum.typeOf(defaultCommissionType) == null) {
                Throw.isBusinessException("请设置默认佣金类型");
            }

            if (ZeroStateEnum.YES.getValue().equals(zeroState) && !DefaultCommissionTypeEnum.NULL.getValue().equals(defaultCommissionType)) {
                Throw.isBusinessException("零元购活动不能设置佣金");
            }

            if (DefaultCommissionTypeEnum.NULL.getValue().equals(defaultCommissionType)) {
//                if (StringUtils.isEmpty(otherEquity)) {
//                    Throw.isBusinessException("请设置其他权益");
//                }
            } else if (DefaultCommissionTypeEnum.COMMISSION.getValue().equals(defaultCommissionType)) {
                if (commissionAmt == null || commissionAmt.compareTo(BigDecimal.ZERO) <= 0) {
                    Throw.isBusinessException("请设置佣金");
                }

                actCommissionAmt = commissionAmt;

                // 固定佣金不能大于等于活动价格
                // 如果是阶梯价格，固定佣金不能大于等于阶梯最小价格
                if (StepPriceStateEnum.YES.getValue().equals(stepPriceState)) {
                    if (commissionAmt.compareTo(minActivePrice) >= 0) {
                        Throw.isBusinessException("固定金额不能大于等于活动阶梯最小价格");
                    }
                } else {
                    if (commissionAmt.compareTo(activePrice) >= 0) {
                        Throw.isBusinessException("固定金额不能大于等于活动价格");
                    }
                }
            } else if (DefaultCommissionTypeEnum.COMMISSION_RATE.getValue().equals(defaultCommissionType)) {
                if (commissionRate == null || commissionRate.compareTo(BigDecimal.ZERO) <= 0) {
                    Throw.isBusinessException("请设置佣金比例");
                }

                actCommissionAmt = activePrice.multiply(commissionRate).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_DOWN);
            }

            if (agentNumState == null || AgentNumStateEnum.typeOf(agentNumState) == null) {
                Throw.isBusinessException("设置推广经纪人类型值错误");
            }

            if (AgentNumStateEnum.NO.getValue().equals(agentNumState) && CollectionUtils.isEmpty(agentIds)) {
                Throw.isBusinessException("请选择推广的经纪人");
            }
        }

        // 限制 阶梯间差价须≤（阶梯 1 价格-红包-佣金）
        if (StepPriceStateEnum.YES.getValue().equals(stepPriceState)) {
            // 根据报名人数升序
            List<ActiveStepPriceSonDto> activeStepPriceSons = activeStepPrices.stream()
                    .sorted(Comparator.comparing(ActiveStepPriceSonDto::getEnrollNum))
                    .collect(Collectors.toList());
            // 第一阶梯
            ActiveStepPriceSonDto firstActiveStepPriceSonDto = activeStepPriceSons.get(0);
            BigDecimal firstEnrollPrice = firstActiveStepPriceSonDto.getEnrollPrice();

            // 第二阶梯
            ActiveStepPriceSonDto secondActiveStepPriceSonDto = activeStepPriceSons.get(1);
            BigDecimal secondEnrollPrice = secondActiveStepPriceSonDto.getEnrollPrice();

            // 阶梯间差价须≤（阶梯 1 价格-红包-佣金）
            BigDecimal diffAmt = firstEnrollPrice.subtract(secondEnrollPrice);
            BigDecimal tmpSubAmt = firstEnrollPrice.subtract(firstRedPacketAmt).subtract(actCommissionAmt);
            if(diffAmt.compareTo(tmpSubAmt) > 0){
                Throw.isBusinessException("阶梯间差价须≤(阶梯1价格-红包-佣金)");
            }

            // 第三阶梯
            if (activeStepPriceSons.size() > 2) {
                ActiveStepPriceSonDto threeActiveStepPriceSonDto = activeStepPriceSons.get(2);
                BigDecimal threeEnrollPrice = threeActiveStepPriceSonDto.getEnrollPrice();

                // 阶梯间差价须≤（阶梯 1 价格-红包-佣金）
                diffAmt = firstEnrollPrice.subtract(threeEnrollPrice);
                if(diffAmt.compareTo(tmpSubAmt) > 0){
                    Throw.isBusinessException("阶梯间差价须≤(阶梯1价格-红包-佣金)");
                }
            }
        }

        // 报名次数限制必填
        Integer limitEnrollNum = activeReleaseDto.getLimitEnrollNum();
//        if (limitEnrollNum == null || limitEnrollNum <= 0) {
//            Throw.isBusinessException("报名次数限制必须大于0个");
//        }

        // 核销方式必填
        Integer verifyMethod = activeReleaseDto.getVerifyMethod();
        if (verifyMethod == null || VerifyMethodEnum.typeOf(verifyMethod) == null) {
            Throw.isBusinessException("请设置核销方式");
        }

        // 报名信息必填，最多添加6个，单选内容最少2个，最多10个
        List<ActiveEnrollInfoSonDto> activeEnrollInfos = activeReleaseDto.getActiveEnrollInfos();
        if (!CollectionUtils.isEmpty(activeEnrollInfos)) {
            if (activeEnrollInfos.size() > 10) {
                Throw.isBusinessException("报名信息最多支持添加10个");
            }

            for (ActiveEnrollInfoSonDto activeEnrollInfo : activeEnrollInfos) {
                // 类型(1-填写项，2-单选项，3-多选项)
                Integer type = activeEnrollInfo.getType();
                if (type == null || ActiveEnrollInfoTypeEnum.typeOf(type) == null) {
                    Throw.isBusinessException("报名信息错误");
                }

                if (ActiveEnrollInfoTypeEnum.SINGLE.getValue().equals(type)) {
                    List<ActiveEnrollInfoOptionDto> activeEnrollInfoOptions = activeEnrollInfo.getActiveEnrollInfoOptions();
                    if (CollectionUtils.isEmpty(activeEnrollInfoOptions)) {
                        Throw.isBusinessException("报名信息错误");
                    }

                    if (activeEnrollInfoOptions.size() < 2) {
                        Throw.isBusinessException("报名信息单选项最少2个");
                    }

                    if (activeEnrollInfoOptions.size() > 10) {
                        Throw.isBusinessException("报名信息单选项最多10个");
                    }
                }

                if (ActiveEnrollInfoTypeEnum.MULTIPLE.getValue().equals(type)) {
                    List<ActiveEnrollInfoOptionDto> activeEnrollInfoOptions = activeEnrollInfo.getActiveEnrollInfoOptions();
                    if (CollectionUtils.isEmpty(activeEnrollInfoOptions)) {
                        Throw.isBusinessException("报名信息错误");
                    }

                    if (activeEnrollInfoOptions.size() < 2) {
                        Throw.isBusinessException("报名信息多选项最少2个");
                    }

                    if (activeEnrollInfoOptions.size() > 10) {
                        Throw.isBusinessException("报名信息多选项最多10个");
                    }
                }
            }
        }

        if (ActiveStateEnum.NO_START.getValue().equals(activeState)) {
            // 判断商家发布活动次数是否足够
            BusinessVo businessVo = businessApi.getActiveCount(activeReleaseDto.getUserId(), activeReleaseDto.getBusinessId()).unpack();
            if (businessVo != null) {
                Integer activeCount = businessVo.getActiveCount();
                if (activeCount < 1) {
                    Throw.isBusinessException("发布活动次数不足");
                }
            }
        }

        TbActivePo tbActivePo = new TbActivePo();
        BeanUtils.copyProperties(activeReleaseDto, tbActivePo);
        tbActivePo.setContent(JSON.toJSONString(activeContents));
        // 活动状态（1-仅保存，2-去发布）
        tbActivePo.setActiveState(ActiveStateEnum.NO_RELEASE.getValue().equals(activeState)
                ? ActiveStateEnum.NO_RELEASE.getValue()
                : ActiveStateEnum.NO_START.getValue());
        tbActivePo.setActiveNo(NoUtils.getActiveNo());
        // 库存改成去totalStock字段
        Integer stock = Optional.ofNullable(activeReleaseDto.getTotalStock())
                .orElse(enrollNum);
        tbActivePo.setTotalStock(stock);
        tbActivePo.setRemainStock(stock);
        tbActivePo.setStartTime(startLocalDateTime);
        tbActivePo.setEndTime(endLocalDateTime);
        tbActivePo.setValidStartTime(validStartLocalDateTime);
        tbActivePo.setValidEndTime(validEndLocalDateTime);
        tbActivePo.setFirstRedPacketAmt(activeRedPacket == null ? BigDecimal.ZERO : activeRedPacket.getFirstRedPacketAmt());
        tbActivePo.setCreateTime(nowLocalDateTime);
        if (ActiveStateEnum.NO_START.getValue().equals(tbActivePo.getActiveState())) {
            tbActivePo.setReleaseTime(nowLocalDateTime);
        }

        return saveEnrollActiveData(activeReleaseDto, tbActivePo, nowLocalDateTime);
    }

    private Long saveEnrollActiveData(ActiveReleaseDto activeReleaseDto, TbActivePo tbActivePo, LocalDateTime nowLocalDateTime) {
        ActiveRedPacketSonDto activeRedPacket = activeReleaseDto.getActiveRedPacket();
        Long activeId = tbActivePo.getId();
        TransactionStatus transaction = transactionManager.getTransaction(new DefaultTransactionAttribute());

        try {
            // 添加活动数据
            int count;
            if (tbActivePo.getId() == null) {
                // 添加活动
                count = activeMapper.insert(tbActivePo);
            } else {
                // 修改活动
                count = activeMapper.updateById(tbActivePo);

                // 删除活动阶梯数据
                activeStepPriceMapper.delete(new QueryWrapper<TbActiveStepPricePo>().eq("active_id", activeId));

                // 删除活动报名信息数据
                activeEnrollInfoMapper.delete(new QueryWrapper<TbActiveEnrollInfoPo>().eq("active_id", activeId));

                // 删除活动经纪人关联数据
                activeAgentMapper.delete(new QueryWrapper<TbActiveAgentPo>().eq("active_id", activeId));

                // 删除活动红包数据
                activeRedPacketMapper.delete(new QueryWrapper<TbActiveRedPacketPo>().eq("active_id", activeId));
            }
            if (count == 0) {
                log.error("添加活动失败，保存活动数据异常");
                Throw.isBusinessException("添加活动失败");
            }
            activeId = tbActivePo.getId();

            // 添加活动标签关联
            List<Long> labelIds = Collections.emptyList();
            if (!CollectionUtils.isEmpty(activeReleaseDto.getLabels())) {
                labelIds = activeReleaseDto.getLabels().stream().map(ActiveLabelDto::getId).collect(Collectors.toList());
            }
            activeLabelService.saveActiveLabels(activeId, labelIds);

            // 添加活动阶梯关联数据
            if (StepPriceStateEnum.YES.getValue().equals(activeReleaseDto.getStepPriceState())) {
                for (ActiveStepPriceSonDto activeStepPrice : activeReleaseDto.getActiveStepPrices()) {
                    TbActiveStepPricePo tbActiveStepPricePo = new TbActiveStepPricePo();
                    tbActiveStepPricePo.setBusinessId(activeReleaseDto.getBusinessId());
                    tbActiveStepPricePo.setActiveId(activeId);
                    tbActiveStepPricePo.setEnrollNum(activeStepPrice.getEnrollNum());
                    tbActiveStepPricePo.setEnrollPrice(activeStepPrice.getEnrollPrice());
                    tbActiveStepPricePo.setCreateTime(nowLocalDateTime);

                    count = activeStepPriceMapper.insert(tbActiveStepPricePo);
                    if (count == 0) {
                        log.error("添加活动失败，保存活动阶梯关联数据异常");
                        Throw.isBusinessException("添加活动失败");
                    }
                }
            }

            // 添加活动报名信息数据
            List<ActiveEnrollInfoSonDto> activeEnrollInfos = activeReleaseDto.getActiveEnrollInfos();
            if (!CollectionUtils.isEmpty(activeEnrollInfos)) {
                for (ActiveEnrollInfoSonDto activeEnrollInfo : activeEnrollInfos) {
                    TbActiveEnrollInfoPo tbActiveEnrollInfoPo = new TbActiveEnrollInfoPo();
                    tbActiveEnrollInfoPo.setBusinessId(activeReleaseDto.getBusinessId());
                    tbActiveEnrollInfoPo.setActiveId(activeId);
                    tbActiveEnrollInfoPo.setType(activeEnrollInfo.getType());
                    tbActiveEnrollInfoPo.setTitle(activeEnrollInfo.getTitle());
                    if (ActiveEnrollInfoTypeEnum.SINGLE.getValue().equals(activeEnrollInfo.getType())
                            || ActiveEnrollInfoTypeEnum.MULTIPLE.getValue().equals(activeEnrollInfo.getType())) {
                        tbActiveEnrollInfoPo.setContent(JSON.toJSONString(activeEnrollInfo.getActiveEnrollInfoOptions()));
                    }
                    tbActiveEnrollInfoPo.setMustState(activeEnrollInfo.getMustState());
                    tbActiveEnrollInfoPo.setSort(activeEnrollInfo.getSort());
                    tbActiveEnrollInfoPo.setCreateTime(nowLocalDateTime);
                    count = activeEnrollInfoMapper.insert(tbActiveEnrollInfoPo);
                    if (count == 0) {
                        log.error("添加活动失败，保存活动报名信息数据异常");
                        Throw.isBusinessException("添加活动失败");
                    }
                }
            }

            // 添加活动经纪人关联数据
            if (AgentNumStateEnum.NO.getValue().equals(activeReleaseDto.getAgentNumState()) && !CollectionUtils.isEmpty(activeReleaseDto.getAgentIds())) {
                for (Long agentId : activeReleaseDto.getAgentIds()) {
                    TbActiveAgentPo tbActiveAgentPo = new TbActiveAgentPo();
                    tbActiveAgentPo.setBusinessId(activeReleaseDto.getBusinessId());
                    tbActiveAgentPo.setActiveId(activeId);
                    tbActiveAgentPo.setAgentId(agentId);
                    tbActiveAgentPo.setCreateTime(nowLocalDateTime);

                    count = activeAgentMapper.insert(tbActiveAgentPo);
                    if (count == 0) {
                        log.error("添加活动失败，保存活动经纪人关联数据异常");
                        Throw.isBusinessException("添加活动失败");
                    }
                }
            }

            // 添加活动红包数据
            if (activeRedPacket != null) {
                TbActiveRedPacketPo tbActiveRedPacketPo = new TbActiveRedPacketPo();
                tbActiveRedPacketPo.setBusinessId(activeReleaseDto.getBusinessId());
                tbActiveRedPacketPo.setActiveId(activeId);
                tbActiveRedPacketPo.setTitle("新人首单优惠");
                tbActiveRedPacketPo.setAmt(activeRedPacket.getFirstRedPacketAmt());
                tbActiveRedPacketPo.setActiveTitle(activeReleaseDto.getActiveTitle());
                tbActiveRedPacketPo.setTotalNum(activeRedPacket.getRedPacketNum());
                tbActiveRedPacketPo.setRemainNum(activeRedPacket.getRedPacketNum());
                tbActiveRedPacketPo.setValidDay(activeRedPacket.getValidDay());
                tbActiveRedPacketPo.setCreateTime(nowLocalDateTime);

                count = activeRedPacketMapper.insert(tbActiveRedPacketPo);
                if (count == 0) {
                    log.error("添加活动失败，保存活动红包数据异常");
                    Throw.isBusinessException("添加活动失败");
                }
            }

            // 营销活动 - 拼团
            if (PromotionTypeEnum.GROUP_BUY.name().equals(activeReleaseDto.getPromotionType())) {
                activeReleaseDto.setId(tbActivePo.getId());
                activeGroupBuyService.saveGroupBuyActive((GroupBuyActiveReleaseDto) activeReleaseDto);
            }

            // 如果是发布活动，则扣除商家活动次数，并记录活动次数流水
            if (ActiveStateEnum.NO_START.getValue().equals(tbActivePo.getActiveState())) {
                UpdateActiveCountDto updateActiveCountDto = new UpdateActiveCountDto();
                updateActiveCountDto.setBusinessId(activeReleaseDto.getBusinessId());
                updateActiveCountDto.setUserId(activeReleaseDto.getUserId());
                updateActiveCountDto.setRelationId(activeId);
                updateActiveCountDto.setTradeActiveCount(1);
                updateActiveCountDto.setTradeType(ActiveCountTradeTypeEnum.RELEASE_ACTIVE.getValue());
                updateActiveCountDto.setTradeTime(nowLocalDateTime);
                Boolean updateState = businessApi.subActiveCount(updateActiveCountDto).unpack();
                if (!updateState) {
                    log.error("添加活动失败，扣除发布活动个数异常");
                    Throw.isBusinessException("发布活动次数不足");
                }
            }

            transactionManager.commit(transaction);
        } catch (Exception e) {
            //回滚事务
            transactionManager.rollback(transaction);
            log.error("<添加报名活动>事务异常回滚", e);
            Throw.isBusinessException(e.getMessage());
        }

        return activeId;
    }

}
